
//  1. 需要知道aimationClip

import { animation, AnimationClip, Sprite, SpriteFrame, UITransform } from "cc";
import { PlayerStateMachine } from "../Script/Player/PlayerStateMachine";

import ResourceManager from "../Runtime/ResourceManager";
import { StateMechine } from "./StateMechine";

const ANIMATION_SPEED=1/8;

//  2. 需要有播放动画的能力 animationClip
export default class State{
  private animationClip :AnimationClip
  constructor(
    private fsm:StateMechine,
    private path:string,
    private wrapMode : AnimationClip.WrapMode = AnimationClip.WrapMode.Normal)
    {
      this.init();
    }

    async init(){
      //通过该ResourceManager 获取到关键帧
      const promise =  ResourceManager.Instance.loadRes(this.path);
      this.fsm.waitingList.push(promise)
      const spriteFrames =await promise;

      this.animationClip = new AnimationClip();
      this.animationClip.duration = 1.0; // 整个动画剪辑的周期

      const track  = new animation.ObjectTrack(); // 创建一个向量轨道
      track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame') // 指定轨道路径，即指定目标对象为 "Foo" 子节点的 "position" 属性
      const frame :Array<[number,SpriteFrame]> = spriteFrames.map((item,index)=>[ANIMATION_SPEED*index,item])
      track.channel.curve.assignSorted(frame);

      // 最后将轨道添加到动画剪辑以应用
      this.animationClip.name = this.path;
      this.animationClip.addTrack(track);
      this.animationClip.duration = frame.length *ANIMATION_SPEED;
      this.animationClip.wrapMode = this.wrapMode;
    }

    run() {
      if (this.fsm.animationComponent.defaultClip?.name === this.animationClip.name) {
        return
      }
      this.fsm.animationComponent.defaultClip = this.animationClip;
      this.fsm.animationComponent.play();
  }

}
